package com.xhy.documents_collection.utils;

import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.exception.BaseException;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;

/**
 * Author: Xhy
 * CreateTime: 2022-12-18 16:08
 */
public class Template {

    public static boolean verify(String temp) {
        if (ObjectUtils.isEmpty(temp)){
            return true;
        }
        if (temp.length() > 1024){
            return false;
        }
        // 不能出现+ / \
        char[] chars = temp.toCharArray();
        int res = 0;
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if ( c == '+' || c == '\\' || c == '/'){
                return false;
            }
            if (c == '{') {
                res++;
            }
            if (c == '}') {
                res--;
            }
            if (res < 0){
                return false;
            }
        }


        return res == 0;
    }

    public static String parseTemp(String temp, User user) throws Exception {
        // base case
        if (temp.indexOf("{") == -1) {
            return temp;
        }
        // 模板开始位置
        int start = 0;
        // 模板结束位置
        int end = 0;
        char[] chars = temp.toCharArray();
        boolean flag = false;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                start = i;
            }
            if (chars[i] == '}') {
                end = i;
                flag = true;
            }
            // 起始位置和终止位置都找到了
            if (flag) {
                String substring = temp.substring(start + 1, end);
                // 不能获得密码
                if (substring.equals("password")){
                    throw new BaseException(500,"不可用用户密码作为模板变量");
                }
                Field field = user.getClass().getDeclaredField(substring);
                field.setAccessible(true);
                String a = "{" + substring + "}";
                String s1 = field.get(user).toString();
                temp = temp.replace(a, s1);
                return parseTemp(temp, user);
            }
        }

        return temp;
    }
}
